import winston, { createLogger } from "winston";
import * as path from "path";
import * as fs from "fs";

// 确保logs目录存在
const logDir = path.join(process.cwd(), "logs");
if (!fs.existsSync(logDir)) {
  fs.mkdirSync(logDir, { recursive: true });
}

export const winstonInstance = createLogger({
  level: process.env.LOG_LEVEL || "info", // 支持环境变量控制日志级别
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.timestamp({
          format: "YYYY-MM-DD HH:mm:ss",
        }),
        winston.format.errors({ stack: true }),
        winston.format.splat(), // 支持字符串插值
        winston.format.json(), // 先转换为JSON以便处理复杂对象
        winston.format.colorize({
          all: true,
          colors: {
            error: "red",
            warn: "yellow",
            info: "cyan",
            debug: "green",
            verbose: "magenta",
          },
        }),
        winston.format.printf(({ timestamp, level, message, stack, context, ...meta }) => {
          // 日志级别图标和边框映射
          const levelConfig = {
            error: { icon: "❌", border: "═══════════════════════════════════════" },
            warn: { icon: "⚠️ ", border: "───────────────────────────────────────" },
            info: { icon: "📝", border: "┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈┈" },
            debug: { icon: "🔍", border: "┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄" },
            verbose: { icon: "💬", border: "⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯⋯" },
          };

          // 获取纯净的日志级别（去除颜色代码）
          const cleanLevel = level.replace(/\x1b\[[0-9;]*m/g, "");
          const config = levelConfig[cleanLevel] || { icon: "📋", border: "·········································" };

          // 确定日志来源
          let source = "[NestWinston]";
          if (context && typeof context === "string") {
            if (context.includes("Service") || context.includes("Controller")) {
              source = `[${context}]`;
            } else if (context === "HTTP" || context === "RouterExplorer" || context === "RoutesResolver") {
              source = "[Nest]";
            } else if (context === "InstanceLoader" || context === "NestFactory") {
              source = "[Nest]";
            } else {
              source = `[${context}]`;
            }
          }

          // 基础日志格式 - 更美观的布局，在最前方显示来源（黄色）
          let logMessage = `\n${config.border}\n\x1b[33m${source}\x1b[0m ${config.icon} ${timestamp} | ${level} | ${message}`;

          // 如果有错误堆栈，添加到日志中
          if (stack && typeof stack === "string") {
            logMessage += `\n🔥 错误堆栈:\n${stack
              .split("\n")
              .map((line) => `   ${line}`)
              .join("\n")}`;
          }

          logMessage += `\n${config.border}\n`;

          return logMessage;
        }),
      ),
    }),
    // 错误日志文件
    new winston.transports.File({
      filename: path.join(logDir, "error.log"),
      level: "error",
      format: winston.format.combine(
        winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        winston.format.errors({ stack: true }),
        winston.format.json(),
      ),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
    }),
    // 组合日志文件（所有级别）
    new winston.transports.File({
      filename: path.join(logDir, "combined.log"),
      format: winston.format.combine(
        winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        winston.format.errors({ stack: true }),
        winston.format.json(),
      ),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
    }),
    // 应用日志文件（info及以上级别）
    new winston.transports.File({
      filename: path.join(logDir, "app.log"),
      level: "info",
      format: winston.format.combine(
        winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        winston.format.printf(({ timestamp, level, message, context, stack }) => {
          const logMessage = `${timestamp} [${level.toUpperCase()}] ${context ? `[${context}] ` : ""}${message}`;
          return stack && typeof stack === "string" ? `${logMessage}\n${stack}` : logMessage;
        }),
      ),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
    }),
  ],
  // 添加异常处理
  exceptionHandlers: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.errors({ stack: true }),
        winston.format.printf(({ timestamp, message, stack }) => {
          return `\n🚨🚨🚨 未捕获异常 🚨🚨🚨\n时间: ${timestamp}\n消息: ${message}\n堆栈:\n${stack && typeof stack === "string" ? stack : "无堆栈信息"}\n🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨\n`;
        }),
      ),
    }),
  ],
  rejectionHandlers: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.timestamp(),
        winston.format.errors({ stack: true }),
        winston.format.printf(({ timestamp, message, stack }) => {
          return `\n💥💥💥 未处理的Promise拒绝 💥💥💥\n时间: ${timestamp}\n消息: ${message}\n堆栈:\n${stack && typeof stack === "string" ? stack : "无堆栈信息"}\n💥💥💥💥💥💥💥💥💥💥💥💥💥💥💥💥💥💥\n`;
        }),
      ),
    }),
  ],
});

export const createStartupLogger = (url: string) => {
  return createLogger({
    transports: [
      new winston.transports.Console({
        format: winston.format.combine(
          winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
          winston.format.colorize({ all: true }),
          winston.format.printf(({ timestamp, level, message }) => {
            return `\n🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉\n✅ ${timestamp} | 🚀 NestJS 服务器启动完成!\n🌐 访问地址: ${url}\n🎯 API 前缀: /api/v1/\n📝 日志级别: ${process.env.LOG_LEVEL || "info"}\n🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉🎉\n`;
          }),
        ),
      }),
      // 启动日志文件
      new winston.transports.File({
        filename: path.join(logDir, "startup.log"),
        format: winston.format.combine(
          winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
          winston.format.printf(({ timestamp, message }) => {
            return `${timestamp} | NestJS 服务器启动完成! 访问地址: ${url}`;
          }),
        ),
        maxsize: 5242880, // 5MB
        maxFiles: 5,
      }),
    ],
  });
};

export const errorLogger = createLogger({
  transports: [
    new winston.transports.Console({
      format: winston.format.combine(
        winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        winston.format.errors({ stack: true }),
        winston.format.colorize({ all: true }),
        winston.format.printf(({ timestamp, message, stack }) => {
          return `\n💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀\n❌ ${timestamp} | 🚨 NestJS 应用启动失败!\n📝 错误信息: ${message}\n${stack && typeof stack === "string" ? `🔥 错误堆栈:\n${stack}` : ""}\n💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀💀\n`;
        }),
      ),
    }),
    // 错误启动日志文件
    new winston.transports.File({
      filename: path.join(logDir, "startup-error.log"),
      format: winston.format.combine(
        winston.format.timestamp({ format: "YYYY-MM-DD HH:mm:ss" }),
        winston.format.errors({ stack: true }),
        winston.format.printf(({ timestamp, message, stack }) => {
          return `${timestamp} | NestJS 应用启动失败! 错误信息: ${message}${stack && typeof stack === "string" ? `\n错误堆栈:\n${stack}` : ""}`;
        }),
      ),
      maxsize: 5242880, // 5MB
      maxFiles: 5,
    }),
  ],
});
